# -*- coding:utf-8 -*-
# author: lawaiter
# time: 2020/6/24
# brief: 利用mutagen包读取MP3、flac等文件信息


import os
from mutagen import File
from mutagen.mp3 import MP3
from mutagen.flac import FLAC


class GetMp3Info():
    """获取MP3信息"""

    def __init__(self, path):
        self.songFile = MP3(path)
        self.songImage = File(path)
        self.getTitle(path)
        self.getArtist()
        self.getAlbum()
        self.getTime()
        self.getAlbumImage(path)
        self.getSize(path)

    def getTitle(self, path):

        """
        获取歌曲名
        :param path: 文件所在路径，含文件本身的url
        """
        try:
            self.title = str(self.songFile.tags['TIT2'])
        except:
            filename = os.path.basename(path)  # 从地址中获取文件名
            self.title = filename.split('.')[0]  # 去掉文件名后缀
        return self.title

    def getArtist(self):

        """获取歌手"""

        try:
            self.artist = str(self.songFile.tags['TPE1'])
        except:
            self.artist = ''

    def getAlbum(self):

        """获取歌曲专辑名称"""

        try:
            self.album = str(self.songFile.tags['TALB'])
        except:
            self.album = ''

    def getTime(self):

        """获取歌曲的时间长度"""

        time_length = int(self.songFile.info.length)
        min_time = time_length // 60  # 转换为分钟
        sec_time = time_length % 60  # 剩余的转换为秒
        if sec_time < 10:
            sec_time = '0' + str(sec_time)
        else:
            sec_time = str(sec_time)
        self.length = str(min_time) + ":" + sec_time

    def getAlbumImage(self, path):

        """
        获取歌曲的专辑图片
        :param path: 文件所在路径，含文件本身的url
        """
        try:
            art_image = self.songImage.tags['APIC:'].data
            title = self.getTitle(path)
            # 找到该文件对应的上级目录，确定在上级目录下的.album文件夹放置专辑图像
            pathAlbumImage = os.path.dirname(path) + './album'
            # 如果./album文件夹已经存在，直接读取MP3中的专辑图片，并保存
            if os.path.exists(pathAlbumImage):
                with open(pathAlbumImage + '/' + title + '.png', 'wb') as img:
                    img.write(art_image)
            # 如果./album文件夹不存在，先新建该文件夹，再保存
            else:
                os.mkdir(pathAlbumImage)
                with open(pathAlbumImage + '/' + title + '.png', 'wb') as img:
                    img.write(art_image)
        except:
            # 如果MP3中没有专辑图片，就什么都不做
            pass

    def getSize(self, path):

        """
        获取歌曲的大小
        :param path:
        :return:
        """
        self.size = os.path.getsize(path)
        if self.size < 1000:
            self.size = '%i' % self.size + 'self.size'
        elif 1000 <= self.size < 1000000:
            self.size = '%.1f' % float(self.size / 1000) + 'KB'
        elif 1000000 <= self.size < 1000000000:
            self.size = '%.1f' % float(self.size / 1000000) + 'MB'
        else:
            self.size = ''
        return self.size


class GetFlacInfo():
    """获取FLAC信息"""

    def __init__(self, path):
        self.songFile = FLAC(path)
        self.songImage = File(path)
        self.getTitle(path)
        self.getArtist()
        self.getAlbum()
        self.getTime()
        self.getSize(path)
        self.getAlbumImage(path)

    def getTitle(self, path):

        """
        获取歌曲名
        :param songfile: 文件对象
        :param path: 文件地址
        :return title: 文件名称
        """
        try:
            self.title = str(self.songFile.tags['TITlE'][0])
        except:
            filename = os.path.basename(path)  # 从地址中获取文件名
            self.title = filename.split('.')[0]  # 去掉文件名后缀
        return self.title

    def getArtist(self):

        """
        :param songfile: 文件对象
        """
        try:
            self.artist = str(self.songFile.tags['ARTIST'][0])
        except:
            self.artist = ''

    def getAlbum(self):

        """
        :param songfile: 文件对象
        """

        try:
            self.album = str(self.songFile.tags['ALBUM'][0])
        except:
            self.album = ''

    def getTime(self):

        """
        :param songfile: 文件对象
        """

        time_length = int(self.songFile.info.length)
        min_time = time_length // 60  # 转换为分钟
        sec_time = time_length % 60  # 剩余的转换为秒
        if sec_time < 10:
            sec_time = '0' + str(sec_time)
        else:
            sec_time = str(sec_time)
        self.length = str(min_time) + ":" + sec_time

    def getSize(self, path):

        """
        获取歌曲的大小
        :param path:
        :return:
        """
        self.size = os.path.getsize(path)
        if self.size < 1000:
            self.size = '%i' % self.size + 'self.size'
        elif 1000 <= self.size < 1000000:
            self.size = '%.1f' % float(self.size / 1000) + 'KB'
        elif 1000000 <= self.size < 1000000000:
            self.size = '%.1f' % float(self.size / 1000000) + 'MB'
        else:
            self.size = ''
        return self.size

    # TODO 完善读取FLAC文件的专辑图片的业务逻辑
    def getAlbumImage(self, path):

        """
        获取歌曲的专辑图片
        :param path: 文件所在路径，含文件本身的url
        """
        try:
            # art_image = self.songImage.tags['APIC:'].data
            # title = self.getTitle(path)
            # 找到该文件对应的上级目录，确定在上级目录下的.album文件夹放置专辑图像
            pathAlbumImage = os.path.dirname(path) + './album'
            # 如果./album文件夹已经存在，直接读取FLAC中的专辑图片，并保存
            if os.path.exists(pathAlbumImage):
                # with open(pathAlbumImage + '/' + title + '.jpg', 'wb') as img:
                #     img.write(art_image)
                pass
            # 如果./album文件夹不存在，先新建该文件夹，再保存
            else:
                os.mkdir(pathAlbumImage)
                # with open(pathAlbumImage + '/' + title + '.jpg', 'wb') as img:
                #     img.write(art_image)
        except:
            # 如果FLAC中没有专辑图片，就什么都不做
            pass


if __name__ == '__main__':
    path = '../static/song/Too Proud.FLAC'
    song = GetFlacInfo(path)
    print(song.title, song.artist, song.album, song.length, song.size)
